const express = require('express');
const axios = require('axios');
const cors = require('cors');
const CONFIG = require('./config');
const { initializeDatabase, query, queryOne, pool } = require('./database');

const app = express();
app.use(cors());
app.use(express.json());

// 初始化数据库
initializeDatabase().catch(console.error);

// 获取微信openid
app.post('/api/wechat/login', async (req, res) => {
    try {
        const { code } = req.body;
        
        // 模拟微信登录，生成openid
        const openid = `wx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        
        // 检查用户是否存在
        const existingUser = await queryOne(
            'SELECT * FROM users WHERE openid = ?', 
            [openid]
        );

        let isNewUser = false;
        
        if (!existingUser) {
            // 创建新用户
            await query(
                'INSERT INTO users (openid, last_login) VALUES (?, NOW())',
                [openid]
            );
            isNewUser = true;
        } else {
            // 更新最后登录时间
            await query(
                'UPDATE users SET last_login = NOW() WHERE openid = ?',
                [openid]
            );
        }

        res.json({
            success: true,
            openid,
            isNewUser,
            message: isNewUser ? '新用户首次登录' : '老用户登录成功'
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 设置用户过敏源
app.post('/api/user/set-allergens', async (req, res) => {
    try {
        const { openid, allergens } = req.body;
        
        // 获取用户ID
        const user = await queryOne(
            'SELECT id FROM users WHERE openid = ?',
            [openid]
        );
        
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }

        // 更新用户过敏源
        await query(
            'UPDATE users SET allergens = ?, allergens_set_at = NOW() WHERE id = ?',
            [JSON.stringify(allergens), user.id]
        );

        res.json({ success: true, message: '过敏源设置成功' });
    } catch (error) {
        console.error('设置过敏源错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 设置用户信息
app.post('/api/user/set-settings', async (req, res) => {
    try {
        const { openid, age, gender, dietaryPreferences, healthGoals } = req.body;
        
        // 获取用户ID
        const user = await queryOne(
            'SELECT id FROM users WHERE openid = ?',
            [openid]
        );
        
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }

        // 检查是否已有设置
        const existingSettings = await queryOne(
            'SELECT * FROM user_settings WHERE user_id = ?',
            [user.id]
        );

        if (existingSettings) {
            // 更新现有设置
            await query(
                `UPDATE user_settings 
                 SET age = ?, gender = ?, dietary_preferences = ?, health_goals = ?, updated_at = NOW()
                 WHERE user_id = ?`,
                [age, gender, JSON.stringify(dietaryPreferences), JSON.stringify(healthGoals), user.id]
            );
        } else {
            // 插入新设置
            await query(
                `INSERT INTO user_settings (user_id, age, gender, dietary_preferences, health_goals)
                 VALUES (?, ?, ?, ?, ?)`,
                [user.id, age, gender, JSON.stringify(dietaryPreferences), JSON.stringify(healthGoals)]
            );
        }

        res.json({ success: true, message: '用户设置保存成功' });
    } catch (error) {
        console.error('设置用户信息错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// AI生成定制菜单
app.post('/api/ai/generate-menu', async (req, res) => {
    try {
        const { openid, timeConstraint, mealType } = req.body;
        
        // 获取用户信息和设置
        const user = await queryOne(
            `SELECT u.*, us.age, us.gender, us.dietary_preferences, us.health_goals
             FROM users u
             LEFT JOIN user_settings us ON u.id = us.user_id
             WHERE u.openid = ?`,
            [openid]
        );
        
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }

        const allergens = user.allergens ? JSON.parse(user.allergens) : [];
        const dietaryPreferences = user.dietary_preferences ? JSON.parse(user.dietary_preferences) : [];
        const healthGoals = user.health_goals ? JSON.parse(user.health_goals) : [];

        // 构建AI提示词
        const prompt = `作为营养师，请为${user.age || '25'}岁${user.gender === 'male' ? '男性' : '女性'}设计一份${timeConstraint || '15'}分钟内的${mealType || '早餐'}。
要求：${allergens.length > 0 ? '避免' + allergens.join('、') : '无过敏限制'}。
健康目标：${healthGoals.join('、') || '保持健康'}。
饮食偏好：${dietaryPreferences.join('、') || '无特殊偏好'}。
请提供：1.食谱名称 2.所需食材 3.制作步骤 4.营养特点 5.预计制作时间`;

        // 模拟AI响应
        const aiResponse = await generateMockAIResponse(prompt);

        // 保存AI菜单记录
        await query(
            'INSERT INTO ai_menus (user_id, menu_data, time_constraint, meal_type) VALUES (?, ?, ?, ?)',
            [user.id, JSON.stringify(aiResponse), timeConstraint, mealType]
        );

        res.json({
            success: true,
            menu: aiResponse,
            generatedAt: new Date()
        });
    } catch (error) {
        console.error('生成菜单错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 模拟AI响应
async function generateMockAIResponse(prompt) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    return {
        name: "香蕉燕麦能量粥",
        ingredients: ["香蕉1根", "即食燕麦50g", "牛奶200ml", "核桃碎10g", "蜂蜜5g"],
        steps: [
            "香蕉压成泥状",
            "加入燕麦片和牛奶搅拌均匀",
            "微波炉高火加热2分钟",
            "加入核桃碎和蜂蜜调味"
        ],
        nutrition: "富含膳食纤维、优质蛋白和健康脂肪，低GI值",
        time: 5,
        calories: 280,
        protein: 12,
        carbs: 45,
        fat: 8
    };
}

// 获取用户信息
app.get('/api/user/info/:openid', async (req, res) => {
    try {
        const { openid } = req.params;
        
        const user = await queryOne(
            `SELECT u.*, us.age, us.gender, us.dietary_preferences, us.health_goals
             FROM users u
             LEFT JOIN user_settings us ON u.id = us.user_id
             WHERE u.openid = ?`,
            [openid]
        );
        
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }

        const userInfo = {
            openid: user.openid,
            createdAt: user.created_at,
            lastLogin: user.last_login,
            allergens: user.allergens ? JSON.parse(user.allergens) : [],
            settings: {
                age: user.age,
                gender: user.gender,
                dietaryPreferences: user.dietary_preferences ? JSON.parse(user.dietary_preferences) : [],
                healthGoals: user.health_goals ? JSON.parse(user.health_goals) : []
            }
        };

        res.json({
            success: true,
            userInfo
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取食谱列表
app.get('/api/recipes', async (req, res) => {
    try {
        const { category, maxTime } = req.query;
        let sql = 'SELECT * FROM recipes WHERE 1=1';
        const params = [];

        if (category && category !== 'all') {
            sql += ' AND category = ?';
            params.push(category);
        }

        if (maxTime && maxTime !== 'all') {
            sql += ' AND time <= ?';
            params.push(parseInt(maxTime));
        }

        sql += ' ORDER BY time ASC';

        const recipes = await query(sql, params);
        
        // 解析JSON字段
        const formattedRecipes = recipes.map(recipe => ({
            ...recipe,
            ingredients: JSON.parse(recipe.ingredients)
        }));

        res.json({ success: true, recipes: formattedRecipes });
    } catch (error) {
        console.error('获取食谱错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;
